using System;
using System.Security.Cryptography;

using stefc.geo.lib;

namespace stefc.geo.data
{

	/// <summary>
	/// Handles Configuration Management with GConf
	/// </summary>
	public class Configuration
	{
		private static volatile Configuration instance; 

		private const string APP_PATH = "/apps/geotool";
		
		private const string IS_METRIC = APP_PATH + "/ismetric";
		
		private const string JID = APP_PATH + "/jid";
		
		private const string PASSWORD = APP_PATH + "/password";
		
		private bool isMetric;
		private string jid;
		private string password;
		
		private Configuration()
		{
			this.Load();
		}
		
		public static Configuration Instance
        {
            get
            {
				if (instance==null)
                    instance=new Configuration();
                return instance;
            }
        }

		public bool IsMetric
		{
			get { return this.isMetric; }
			set 
			{
				if(value!=this.isMetric)
				{
					this.isMetric=value;
					this.Set(IS_METRIC, this.isMetric);
				}
			}
		}
		
		public string JId
		{
			get { return this.jid; }
			set
			{
				if(value!=this.jid)
				{
					this.jid=value;
					this.Set(JID, this.jid);
				}
			}
		}
		
		public string Password
		{
			get { return this.password; }
			set
			{
				if(value!=this.password)
				{
					this.password=value;
					this.Set(PASSWORD, this.Crypt(this.password));
				}
			}
		}
						
		public void Load()
		{
			this.isMetric=this.Get(IS_METRIC,true);
			this.jid=this.Get(JID, "unknown@jabber.org");
			this.password=this.Decrypt(this.Get(PASSWORD,String.Empty));
		}
		
		private T Get<T>(string key, T defaultValue)
		{
			return DatabaseManager.Instance.GetValue<T>(key,defaultValue);
		}
		
		private void Set<T>(string key, T value)
		{
			DatabaseManager.Instance.SetValue<T>(key,value);
		}
		
		private string Crypt(string s)
		{
			if(String.IsNullOrEmpty(s))
				return String.Empty;
			return Encryption.EncryptString(s, HASH_CODE);
		}
		
		private string Decrypt(string s)
		{
			if(String.IsNullOrEmpty(s))
				return String.Empty;
			return Encryption.DecryptString(s, HASH_CODE);
		}
		
		private static string HASH_CODE = "5DxE%4v";
	}
}
